package com.pearl.boot;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.ansi.AnsiStyle;
import org.springframework.core.env.Environment;

import java.io.PrintStream;

/**
 * 自定义 Banner
 *
 * @author TangDan
 * @version 1.0
 * @since 2022/9/5
 */
@Getter
@Setter
public class PearlBanner implements Banner {

    public String appName;

    private static final String[] BANNER = new String[]{
            "",
            " _______  ________       _       _______     _____     ",
            "|_   __ \\|_   __  |     / \\     |_   __ \\   |_   _|     ",
            "  | |__) | | |_ \\_|    / _ \\      | |__) |    | |       ",
            "  |  ___/  |  _| _    / ___ \\     |  __ /     | |   _   ",
            " _| |_    _| |__/ | _/ /   \\ \\_  _| |  \\ \\_  _| |__/ |  ",
            "|_____|  |________||____| |____||____| |___||________|  "};
    private static final String SPRING_BOOT = " :: Spring Boot :: ";
    private static final String APP_NAME = "AppName: ";
    private static final String APP_VERSION = "Version: ";
    private static final String PORT = "Port: ";
    private static final String PID = "Pid: ";
    private static final int STRAP_LINE_SIZE = 42;

    @Override
    public void printBanner(Environment environment, Class<?> sourceClass, PrintStream printStream) {
        for (int i = 0; i < BANNER.length; i++) {
            String banner = BANNER[i];
            String value = switch (i) {
                case 2 -> AnsiOutput.toString(AnsiColor.GREEN, APP_NAME, AnsiColor.DEFAULT, AnsiStyle.FAINT, appName);
                case 3 ->
                        AnsiOutput.toString(AnsiColor.GREEN, APP_VERSION, AnsiColor.DEFAULT, AnsiStyle.FAINT, environment.getProperty("project.version"));
                case 4 ->
                        AnsiOutput.toString(AnsiColor.GREEN, PORT, AnsiColor.DEFAULT, AnsiStyle.FAINT, environment.getProperty("server.port"));
                case 5 ->
                        AnsiOutput.toString(AnsiColor.GREEN, PID, AnsiColor.DEFAULT, AnsiStyle.FAINT, environment.getProperty("pid"));
                default -> StrUtil.EMPTY;
            };
            printStream.print(banner);
            printStream.println(value);
        }
        String version = SpringBootVersion.getVersion();
        version = " (v" + version + ")";
        StringBuilder padding = new StringBuilder();
        while (padding.length() < 42 - (version.length() + " :: Spring Boot :: ".length())) {
            padding.append(" ");
        }
        printStream.println(AnsiOutput.toString(AnsiColor.GREEN, " :: Spring Boot :: ", AnsiColor.DEFAULT, padding.toString(), AnsiStyle.FAINT, version));
        printStream.println();
    }
}
